<template>
  <div class="session-list">
    <div class="session-list-header">
      <h2>💬 会话列表</h2>
      <button class="new-session-btn" @click="createNewSession" title="新建会话">
        <plus-icon class="icon" />
      </button>
    </div>
    
    <div class="session-items" ref="sessionItemsRef">
      <div
        v-for="session in sessions"
        :key="session"
        class="session-item"
        :class="{ active: session === currentSession }"
        @click="selectSession(session)"
      >
        <div class="session-content">
          <div class="session-header">
            <span class="session-title">{{ getSessionTitle(session) }}</span>
            <button 
              class="delete-btn" 
              @click.stop="deleteSession(session)"
              title="删除会话"
            >
              <trash-icon class="icon" />
            </button>
          </div>
          <div class="session-preview" v-if="getFirstQuestion(session)">
            {{ getFirstQuestion(session) }}
          </div>
          <div class="session-meta">
            <span class="message-count" v-if="getMessageCount(session) > 0">
              {{ getMessageCount(session) }} 条消息
            </span>
            <span class="session-time">{{ getSessionTime(session) }}</span>
          </div>
        </div>
      </div>
      
      <div v-if="sessions.length === 0" class="empty-sessions">
        <p>还没有会话</p>
        <p class="hint">点击上方按钮创建新会话</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';
import { PlusIcon, TrashIcon } from 'vue-tabler-icons';
import { useStore } from '../store';

const props = defineProps({
  sessions: {
    type: Array,
    required: true
  },
  currentSession: {
    type: String,
    required: true
  }
});

const emits = defineEmits(['select', 'delete', 'create']);

const store = useStore();
const sessionItemsRef = ref(null);

const selectSession = (session) => {
  emits('select', session);
};

const deleteSession = (session) => {
  if (confirm(`确定要删除会话 "${getSessionTitle(session)}" 吗？`)) {
    emits('delete', session);
  }
};

const createNewSession = () => {
  // 直接创建新会话，自动生成ID和标题
  store.addSession();
  emits('create', store.currentSession);
};

const getSessionTitle = (sessionId) => {
  return store.sessionInfo[sessionId]?.title || sessionId;
};

const getLastMessage = (sessionId) => {
  return store.sessionInfo[sessionId]?.lastMessage || '';
};

// 获取第一个问题（用于预览）
const getFirstQuestion = (sessionId) => {
  // 优先使用lastMessage（第一个问题的预览）
  const lastMessage = store.sessionInfo[sessionId]?.lastMessage;
  if (lastMessage) {
    return lastMessage;
  }
  // 如果没有，尝试从消息中获取第一条用户消息
  const messages = store.messages[sessionId];
  if (messages && messages.length > 0) {
    const firstUserMessage = messages.find(msg => msg.isUser);
    if (firstUserMessage) {
      // 提取纯文本
      let text = firstUserMessage.content;
      text = text.replace(/^#{1,6}\s+/gm, '');
      text = text.replace(/```[\s\S]*?```/g, '');
      text = text.replace(/`[^`]+`/g, '');
      text = text.replace(/\[([^\]]+)\]\([^\)]+\)/g, '$1');
      text = text.replace(/[*_~]{1,2}([^*_~]+)[*_~]{1,2}/g, '$1');
      text = text.replace(/\n/g, ' ').replace(/\s+/g, ' ').trim();
      if (text.length > 50) {
        text = text.substring(0, 50) + '...';
      }
      return text;
    }
  }
  return '';
};

const getMessageCount = (sessionId) => {
  return store.messages[sessionId]?.length || 0;
};

const getSessionTime = (sessionId) => {
  const info = store.sessionInfo[sessionId];
  if (!info?.updatedAt && !info?.createdAt) {
    return '';
  }
  
  const timeStr = info.updatedAt || info.createdAt;
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now - date;
  
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
};
</script>

<style scoped>
.session-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
}

.session-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.25rem 1.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.session-list-header h2 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0;
}

.new-session-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-session-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.05);
}

.icon {
  width: 1.25rem;
  height: 1.25rem;
}

.session-items {
  flex: 1;
  overflow-y: auto;
  padding: 0.75rem;
}

.session-items::-webkit-scrollbar {
  width: 6px;
}

.session-items::-webkit-scrollbar-track {
  background: transparent;
}

.session-items::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.session-items::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

.session-item {
  background: white;
  border-radius: 12px;
  margin-bottom: 0.75rem;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 2px solid transparent;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.session-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
}

.session-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
}

.session-content {
  padding: 1rem;
}

.session-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;
}

.session-title {
  font-weight: 600;
  font-size: 0.95rem;
  flex: 1;
  line-height: 1.4;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.session-item.active .session-title {
  color: white;
}

.session-preview {
  font-size: 0.85rem;
  color: #666;
  line-height: 1.4;
  margin-bottom: 0.5rem;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.session-item.active .session-preview {
  color: rgba(255, 255, 255, 0.9);
}

.session-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.75rem;
  color: #999;
  margin-top: 0.5rem;
}

.session-item.active .session-meta {
  color: rgba(255, 255, 255, 0.8);
}

.message-count {
  font-weight: 500;
}

.delete-btn {
  background: transparent;
  border: none;
  padding: 0.25rem 0.5rem;
  opacity: 0.6;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #666;
  border-radius: 4px;
  margin-left: 0.5rem;
  flex-shrink: 0;
}

.session-item.active .delete-btn {
  color: white;
  opacity: 0.8;
}

.delete-btn:hover {
  opacity: 1;
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.session-item.active .delete-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.empty-sessions {
  text-align: center;
  padding: 3rem 1rem;
  color: #999;
}

.empty-sessions p {
  margin: 0.5rem 0;
}

.hint {
  font-size: 0.85rem;
  color: #bbb;
}
</style>
